# -*- coding: utf-8 -*-
"""
Created on Wed Feb  3 21:53:58 2021

@author: 59567
"""
import sys
sys.path.append('../../')
import pandas as pd
import numpy as np
from pandas import read_pickle, to_datetime
from copy import deepcopy
from tjdutils.utils import TjdDate, check_path
import os, shutil
import datetime
from MYSQL.y_assemble import y_assemble_update

def expend_dimension(summary, kind, y_i):
    summary.index = summary['end_datetime']
    summary.sort_index(inplace=True)
    end_datetimes = sorted(list(summary['end_datetime']))
    all_times_idx, all_times_cols = [], []
    for t in end_datetimes:
        all_times_cols.append(t)
        for tt in summary.loc[t, 'test_times']:
            all_times_idx.append(tt)
    all_times_idx = sorted(list(set(all_times_idx)))
    ex_pd = pd.DataFrame(np.nan, index=all_times_idx, columns=all_times_cols)
    for t in end_datetimes:
        for i, tt in enumerate(summary.loc[t, 'test_times']):
            ex_pd.loc[tt, t] = summary.loc[t, kind][i, 0]
    ex_pd.index = pd.to_datetime(ex_pd.index)
    ex_pd.columns = pd.to_datetime(ex_pd.columns)
    return ex_pd


def plot_fill_between(ax, inds, y, y_p, y_name):
    if y_name in [True, False]:
        cc = 'red' if y_name else 'green'
    else:
        cc = 'b'
    ax.fill_between(inds, y, y_p, color=cc, alpha=0.5)


def prepare_y_yp_acc(y_se, y_p_df, y_df, summary, method, correct=False, fd_score=1.25):  # 为红绿蜈蚣图准备数据
    y_p_df, y_df = deepcopy((y_p_df, y_df))
    y_t_f_df = pd.DataFrame(data=np.nan, index=y_df.columns, columns=['acc'])
    print('correct')
    y_p_df.columns = to_datetime(y_p_df.columns)
    y_p_df.index = to_datetime(y_p_df.index)
    summary.index = to_datetime(summary.index)
    for num, c in enumerate(y_p_df.columns):
        if summary.prediction[0] == False:
            r_i = list(y_p_df.index).index(c)
            i = list(y_p_df.columns).index(c)
        else:
            r_i = num + 1
            i = num
            if num >= len(y_p_df.columns):
                break
        if correct:
            upper = summary.loc[c, 'upper_' + method]
            lower = summary.loc[c, 'lower_' + method]
            print(fd)
            if fd > fd_score:
                if y_p_df.iloc[r_i, i] > upper:
                    y_p_df.iloc[r_i, i] = upper
                    print(c, 'correct down from', str(y_p_df.iloc[r_i, i]), 'to:', str(upper), 'by method:', method)
                if y_p_df.iloc[r_i, i] < lower:
                    y_p_df.iloc[r_i, i] = lower
                    print(c, 'correct up from', str(y_p_df.iloc[r_i, i]), 'to:', str(lower), 'by method:', method)
            else:
                print('不需要按照trend修')
        y_p_d = y_p_df.iloc[r_i, i] - y_df.iloc[r_i - 1, i]
        y_d = y_df.iloc[r_i, i] - y_df.iloc[r_i - 1, i]
        if y_p_d * y_d >= 0:
            y_t_f_df.iloc[i, 0] = True
        else:
            y_t_f_df.iloc[i, 0] = False
    return y_p_df, y_t_f_df


def reset_x_tick(hf_df):
    new_idx = []
    for i, t in enumerate(hf_df.index):
        if TjdDate(t).dt['mld'] == t:
            new_idx.append(i)
    return new_idx


def get_month_end_real(hf_df, y, y_name):
    month_end_real = pd.DataFrame(data=None, index=hf_df.index, columns=hf_df.columns)
    y.index = to_datetime(y.index)
    y_se = y.loc[:,y_name]
    for t in month_end_real.index:
        if t in y_se.index:
            month_end_real.loc[t, y_name] = y_se[t]
    return month_end_real

def loading_y():  # 自动获取最新的y_plus_集合.xlsx, 每日重置一次, 放在input文件夹
    today = str(datetime.date.today())
    path = check_path(f"../input/y_plus_集合{today}.xlsx")
    if os.path.exists(path):
        print("laoding%s" % path)
        yyy = pd.read_excel(path, index_col=0)
    else:
        print('loading y集合from mysql........')
        yyy = y_assemble_update().select_all_table()
        yyy.to_excel(path)
        print('loading sucess!!, next loading form local input dir')
    return yyy


if __name__ == "__main__":
    path = "D:/高频中台/output/collector/collector2021_01_28_14_39_23_17/PPI_2021_01_28_17_22_19_06.pkl"
    data = read_pickle(path)
    ex_pd = expend_dimension(data, 'y_test_predictions', 0)